package chaoyue.study.service.impl;

import chaoyue.study.entity.User;
import chaoyue.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LockService {
    @Resource
    private UserMapper userMapper;

    public void getByNameLong(String name) {
        userMapper.selectByNameForUpdate(name);
        longSleep();
    }

    @Transactional
    public void getByNameLongTransactional(String name) {
        List<User> resultList = userMapper.selectByNameForUpdate(name);
        longSleep();
    }

    public void getByNameShort(String name) {
        userMapper.selectByNameForUpdate(name);
    }

    @Transactional
    public void getByNameShortTransactional(String name) {
        userMapper.selectByNameForUpdate(name);
    }

    public void addUserShort(User user) {
        userMapper.insert(user);
    }

    @Transactional
    public void addUserShortTransactional(User user) {
        userMapper.insert(user);
    }

    private void longSleep() {
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
